<?php

/**
 * GET 请求
 *
 * @param $url
 * @return mixed|string
 */

if(!function_exists('sendRequest')) {
    function sendRequest($url)
    {

        if (function_exists('curl_exec')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $data = curl_exec($ch);
            $curl_errno = curl_errno($ch);
            curl_close($ch);
            if ($curl_errno > 0) {
                return 0;
            }

            return $data;
        }

        $opts = array(
            'http' => array(
                'method' => 'GET',
                'timeout' => 2,
            )
        );
        $context = stream_context_create($opts);
        $data = @file_get_contents($url, false, $context);
        if ($data) {
            return $data;
        }

        return 0;
    }
}

/**
 * POST 请求
 *
 * @param       $url
 * @param string $post_data
 * @return mixed|string
 */

if(!function_exists('postRequest')) {
    function postRequest($url, $post_data = '')
    {
        if (!$post_data) {
            return false;
        }

        $data = http_build_query($post_data);
        if (function_exists('curl_exec')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 1);

            //不可能执行到的代码
            if (!$post_data) {
                curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
            } else {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            }
            $data = curl_exec($ch);

            if (curl_errno($ch)) {
                $err = sprintf("curl[%s] error[%s]", $url, curl_errno($ch) . ':' . curl_error($ch));
                trigger_error($err);
            }

            curl_close($ch);
        } else {
            if ($post_data) {
                $opts = array(
                    'http' => array(
                        'method' => 'POST',
                        'header' => "Content-type: application/x-www-form-urlencoded\r\n" . 'Content-Length: ' . strlen($data) . "\r\n",
                        'content' => $data,
                        'timeout' => 2
                    )
                );
                $context = stream_context_create($opts);
                $data = file_get_contents($url, false, $context);
            }
        }

        return $data;
    }
}

